import { ref } from "vue";
import { api } from "src/boot/axios";

export const isLogin = ref(false);
export const checkStatusTimer = ref(null);
export const userInfo = ref({
  user_id: "",
  email: "",
  display_name: "",
  given_name: "",
  surname: "",
  user_principal_name: "",
});
export const OpenNewTab = (url) => {
  const loginData = {
    email: localStorage.getItem("email"),
    token: localStorage.getItem("token"),
  };
  const localStorageJson = JSON.stringify(loginData);
  // to Base64
  const base64 = btoa(
    encodeURIComponent(localStorageJson).replace(
      /%([0-9A-F]{2})/g,
      (match, p1) => String.fromCharCode(parseInt(p1, 16))
    )
  );

  if (url.includes("?")) {
    window.open(url + "&LoginData=" + base64, "_blank");
  } else {
    window.open(url + "?LoginData=" + base64, "_blank");
  }
};

export const RedirectTo = (url) => {
  const loginData = {
    email: localStorage.getItem("email"),
    token: localStorage.getItem("token"),
  };
  const localStorageJson = JSON.stringify(loginData);
  // to Base64
  const base64 = btoa(
    encodeURIComponent(localStorageJson).replace(
      /%([0-9A-F]{2})/g,
      (match, p1) => String.fromCharCode(parseInt(p1, 16))
    )
  );

  if (url.includes("?")) {
    window.location.href = url + "&LoginData=" + base64;
  } else {
    window.location.href = url + "?LoginData=" + base64;
  }
};

export const Dialog = (url, title, onMessage = null) => {
  const loginData = {
    email: localStorage.getItem("email"),
    token: localStorage.getItem("token"),
  };
  const localStorageJson = JSON.stringify(loginData);
  // to Base64
  const base64 = btoa(
    encodeURIComponent(localStorageJson).replace(
      /%([0-9A-F]{2})/g,
      (match, p1) => String.fromCharCode(parseInt(p1, 16))
    )
  );

  if (url.includes("?")) {
    url = url + "&LoginData=" + base64;
  } else {
    url = url + "?LoginData=" + base64;
  }

  // 纯JS实现弹窗对话框
  // 创建遮罩层
  const mask = document.createElement("div");
  mask.style.position = "fixed";
  mask.style.top = "0";
  mask.style.left = "0";
  mask.style.width = "100vw";
  mask.style.height = "100vh";
  mask.style.background = "rgba(0,0,0,0.4)";
  mask.style.zIndex = "9999";
  mask.style.display = "flex";
  mask.style.alignItems = "center";
  mask.style.justifyContent = "center";

  // 创建弹窗容器
  const dialog = document.createElement("div");
  dialog.style.width = "90vw";
  dialog.style.maxWidth = "1200px";
  dialog.style.height = "80vh";
  dialog.style.background = "#fff";
  dialog.style.borderRadius = "8px";
  dialog.style.overflow = "hidden";
  dialog.style.display = "flex";
  dialog.style.flexDirection = "column";
  dialog.style.boxShadow = "0 2px 16px rgba(0,0,0,0.2)";
  dialog.style.position = "relative";

  // 标题栏
  const header = document.createElement("div");
  header.style.display = "flex";
  header.style.justifyContent = "space-between";
  header.style.alignItems = "center";
  header.style.padding = "20px 28px";
  header.style.background = "linear-gradient(90deg, #f8fafc 0%, #e0e7ef 100%)";
  header.style.borderBottom = "1px solid #e3e8ee";
  header.style.boxShadow = "0 2px 8px rgba(0,0,0,0.04)";
  header.style.fontFamily =
    "'PingFang SC', 'Microsoft YaHei', Arial, sans-serif";

  const h3 = document.createElement("h3");
  h3.style.margin = "0";
  h3.style.color = "#333";
  h3.style.fontSize = "18px"; // 调小字体
  h3.innerText = title;

  // 关闭按钮
  const closeBtn = document.createElement("button");
  closeBtn.innerHTML = "&#10005;";
  closeBtn.style.background = "none";
  closeBtn.style.border = "none";
  closeBtn.style.fontSize = "20px";
  closeBtn.style.cursor = "pointer";
  closeBtn.style.width = "32px";
  closeBtn.style.height = "32px";
  closeBtn.style.borderRadius = "50%";
  closeBtn.style.display = "flex";
  closeBtn.style.alignItems = "center";
  closeBtn.style.justifyContent = "center";
  closeBtn.style.transition = "background 0.2s";
  closeBtn.onmouseover = () => (closeBtn.style.background = "#eee");
  closeBtn.onmouseout = () => (closeBtn.style.background = "none");

  // 消息监听器
  const messageHandler = (event) => {
    if (onMessage) {
      // 调用传入的回调函数处理消息，传递整个event对象
      const shouldClose = onMessage(event);

      // 如果回调函数返回true，则关闭对话框
      if (shouldClose) {
        // 关闭对话框
        document.body.removeChild(mask);
        // 移除消息监听器
        window.removeEventListener("message", messageHandler);
      }
    }
  };

  // 添加消息监听器
  if (onMessage) {
    window.addEventListener("message", messageHandler);
  }

  closeBtn.onclick = () => {
    // 移除消息监听器
    if (onMessage) {
      window.removeEventListener("message", messageHandler);
    }
    document.body.removeChild(mask);
  };

  header.appendChild(h3);
  header.appendChild(closeBtn);

  // iframe
  const iframe = document.createElement("iframe");
  iframe.src = url;
  iframe.style.width = "100%";
  iframe.style.height = "100%";
  iframe.style.border = "none";
  iframe.style.flex = "1";
  iframe.allow = "autoplay";

  // 组装
  dialog.appendChild(header);
  dialog.appendChild(iframe);
  mask.appendChild(dialog);

  // 点击遮罩层关闭（可选，若要强制持久可注释掉）
  mask.addEventListener("click", (e) => {
    if (e.target === mask) {
      document.body.removeChild(mask);
    }
  });

  document.body.appendChild(mask);
};

export const handleLoginStatus = async () => {
  try {
    const statusRes = await api.get("/api/v1/user_info", {
      headers: {
        ApiKey: btoa(
          `${localStorage.getItem("token") || ""}` +
            "$$" +
            `${localStorage.getItem("email") || ""}`
        ),
      },
    });

    // 验证响应数据
    if (statusRes && statusRes.data) {
      userInfo.value = statusRes.data;
      isLogin.value = true;

      // 只有在没有定时器的情况下才设置新的定时器
      if (!checkStatusTimer.value) {
        checkStatusTimer.value = setInterval(
          async () => {
            try {
              await handleLoginStatus();
            } catch (error) {
              console.error("定时检查登录状态失败:", error);
              // 如果定时检查失败，清除定时器
              if (checkStatusTimer.value) {
                clearInterval(checkStatusTimer.value);
                checkStatusTimer.value = null;
              }
            }
          },
          1000 * 60 * 30 // 30分钟检查一次
        );
      }
    } else {
      throw new Error("无效的响应数据");
    }
  } catch (e) {
    console.error("检查登录状态失败:", e);
    isLogin.value = false;
    localStorage.removeItem("token");
    localStorage.removeItem("email");

    // 清理定时器
    if (checkStatusTimer.value) {
      clearInterval(checkStatusTimer.value);
      checkStatusTimer.value = null;
    }
  }
};

export const onLogged = async (callback) => {
  if (!localStorage.getItem("token") || !localStorage.getItem("email")) {
    console.log("no login");
    return;
  }
  return new Promise((resolve) => {
    const checkInterval = setInterval(() => {
      console.log("login check...");
      if (isLogin.value) {
        console.log("login success");
        clearInterval(checkInterval);
        if (callback && typeof callback === "function") {
          console.log("login callback");
          callback();
        }
        resolve();
      }
    }, 100);
  });
};

// 为了向后兼容，添加 onLoggedIn 作为 onLogged 的别名
export const onLoggedIn = onLogged;
